package hz.mobileproject.pda.utils;

import android.app.Activity;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.widget.Toast;

import com.blankj.utilcode.util.ToastUtils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * Created by Lc on 2017/12/7.
 */

public class TakePhotoUtil {
    private static TakePhotoUtil takePhotoUtil;
    private Activity mActivity;
    //当前图片路径
    private static String mCurPicPath;
    /**
     * 照片相关-------------------------------------------
     */
    public static final int TAKE_PHOTO_RESULT_CODE = 201;
    public static final int OPEN_PIC_RESULT_CODE = 202;


    private TakePhotoUtil(Activity context) {
        this.mActivity = context;
    }

    public static TakePhotoUtil getInstance(Activity context){
        if(takePhotoUtil == null){
            return new TakePhotoUtil(context);
        }
        takePhotoUtil.setmActivity(context);
        return takePhotoUtil;
    }

    public void setmActivity(Activity mActivity) {
        this.mActivity = mActivity;
    }

    public String getCurPicPath(int requestCode,Intent data) {
        if(requestCode == OPEN_PIC_RESULT_CODE && data != null){
            mCurPicPath = getPathFromOpenPic(data);
            return mCurPicPath;
        }else if(requestCode == TAKE_PHOTO_RESULT_CODE){
            return mCurPicPath;
        }
        return "";
    }

    /**
     *  打开系统相册
     */
    public void openPic() {
        //避免错误导致获取到上一张图片路径   先清空
        mCurPicPath = "";
        Intent photoPickerIntent = new Intent(
                Intent.ACTION_PICK,
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        photoPickerIntent.setType("image/*");
        mActivity.startActivityForResult(photoPickerIntent, OPEN_PIC_RESULT_CODE);
    }


    /**
     * 调用系统照相机
     */
    public String takePhoto() {
        //避免错误导致获取到上一张图片路径   先清空
        mCurPicPath = "";
        String resultPath = "";
        String SDState = Environment.getExternalStorageState();
        if((Environment.MEDIA_MOUNTED).equals(SDState)) {
            String imageFilePath = mActivity.getExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath();
            SimpleDateFormat mFormatter = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA);
            Date date = new Date();
            //和后台定义 照片的文件名
            String timestamp = "/" + mFormatter.format(date) + ".jpg";
            File imageFile = new File(imageFilePath,timestamp);
            resultPath = imageFile.getAbsolutePath();
            Uri imageFileUri = Uri.fromFile(imageFile)!= null ? Uri.fromFile(imageFile) : null;

            Intent intent = new Intent();
            intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);

            //7.0内存权限
            Uri data;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                // "hz.mobileproject.pda.fileprovider"即是在清单文件中配置的authorities
                data = FileProvider.getUriForFile((Context) mActivity, "hz.mobileproject.pda.fileprovider", imageFile);
                // 给目标应用一个临时授权
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            } else {
                data = imageFileUri;
            }
            intent.putExtra(MediaStore.EXTRA_OUTPUT,data);
            try{
                mActivity.startActivityForResult(intent, TAKE_PHOTO_RESULT_CODE);
            }catch (Exception e){
                Toast.makeText(mActivity,"没有拍照权限，请在设置页开启",Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }
        }else {
            ToastUtils.showLong("内存卡不存在");
        }
        mCurPicPath = resultPath;
        return resultPath;
    }


    /**
     * 从系统相册获得路径
     * @param data
     * @return
     */
    private String getPathFromOpenPic(Intent data){
        //打开系统相册
        String[] pojo = {MediaStore.Images.Media.DATA};
        Uri uri = data.getData();
        CursorLoader cursorLoader = new CursorLoader(mActivity, uri, pojo, null,null, null);
        Cursor cursor = cursorLoader.loadInBackground();
        cursor.moveToFirst();
        String path = cursor.getString(cursor.getColumnIndex(pojo[0]));
        mCurPicPath = path;
        return path;
    }
}
